﻿using System;
using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Serializer.Stream.Extension;
using System.Net.DnsToolkit.Serializer.Stream.Compression;

namespace System.Net.DnsToolkit.Serializer.Stream.Writer {
    public class RRWriter : IRRWriter<System.IO.Stream> {

        private readonly IRecordWriterProvider<System.IO.Stream> _recordWriterProvider;
        public RRWriter(IRecordWriterProvider<System.IO.Stream> recordWriterProvider) {
            _recordWriterProvider = recordWriterProvider;
        }

        public void Write(System.IO.Stream destination, IRR rr, ICompressionContext cc) {
            Write(destination, rr, (CompressionContext)cc);
        }

        private void Write(System.IO.Stream destination, IRR rr, CompressionContext cc) {

            destination.WriteDomainName(rr.Name, cc);

            destination.Write16((ushort)rr.RRType);
            destination.Write16((ushort)rr.RRClass);
            destination.Write32(rr.Ttl);
            destination.Write16(rr.RDLength);

            IRecordWriter<System.IO.Stream> recordWriter = _recordWriterProvider.Provide(rr.RData.QType);
            recordWriter.Write(rr.RData, destination, cc);

        }
    }
}
